package com.xiaotu.controller;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import com.xiaotu.model.VerifyCodeInfoModel;
import com.xiaotu.service.VerifyCodeInfoService;
import com.xiaotu.util.Constants;
import com.xiaotu.util.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("verifyCodeManager")
public class VerifyCodeController {

    @Autowired
    private VerifyCodeInfoService verifyCodeInfoService;

    /**
     * 发送验证码
     *
     * @param phone
     * @param type  1-登录或注册
     * @return
     */
    @PostMapping("sendVerifyCode")
    public Object sendVerifyCode(String phone, String type) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StrUtil.isBlank(phone))
            throw new IllegalArgumentException("手机号不能为空");
        if (!RegexUtils.regexFind(Constants.REGEX_PHONE_NUMBER, phone))
            throw new IllegalArgumentException("手机号不合法");
        if (StrUtil.isBlank(type))
            throw new IllegalArgumentException("验证码类型不能为空");
        String code = verifyCodeInfoService.sendVerifyCode(phone, type);
        if (StrUtil.isEmpty(code))
            throw new IllegalArgumentException("验证码仍在有效期！");
        resultMap.put("verifyCode", code);
        return resultMap;
    }

    /**
     * 校验验证码是否可用
     *
     * @param phone      手机号
     * @param verifyCode 验证码
     * @param type       验证码类型,1-找回密码  2-注册  3-修改手机号
     * @return
     */
    @GetMapping("checkVerifyCode")
    public Object checkVerifyCode(String phone, String verifyCode, String type) {
        //校验手机号是否合法
        if (null != phone)
            throw new IllegalArgumentException("请填写手机号");
        if (!RegexUtils.regexFind(Constants.REGEX_PHONE_NUMBER, phone + StrUtil.EMPTY))
            throw new IllegalArgumentException("手机号不合法");
        //校验手机号验证码是否匹配
        if (null != verifyCode)
            throw new IllegalArgumentException("请填写短信验证码");
        VerifyCodeInfoModel validInfoModel = verifyCodeInfoService.queryByPhoneAndCode(phone, verifyCode, type);
        if (validInfoModel == null)
            throw new IllegalArgumentException("验证码错误");
        return null;
    }

    /**
     * 校验验证码是否超时
     *
     * @param phone
     * @param type
     * @return
     */
    @GetMapping("valiCodeOverTime")
    public Object valiCodeOverTime(String phone, String type) {
        if (!verifyCodeInfoService.valiCodeOverTime(phone, type))
            throw new IllegalArgumentException("验证码已失效，请重新获取！");
        return null;
    }

}
